package com.sfh.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.sfh.base.BaseController;
import com.sfh.base.ReturnData;
import com.sfh.base.util.StringUtil;
import com.sfh.controller.rsp.RspConSume;
import com.sfh.controller.rsp.RspMass;
import com.sfh.controller.rsp.RspNote;
import com.sfh.controller.rsp.RspUser;
import com.sfh.controller.task.TaskUserWealthCharm;
import com.sfh.req.ReqBase;
import com.sfh.req.ReqConsumeWealth;
import com.sfh.req.ReqPage;
import com.sfh.req.ReqQueryUser;
import com.sfh.req.ReqUpdatePwd;
import com.sfh.req.ReqUserActivateVip;
import com.sfh.req.ReqUserLogin;
import com.sfh.req.ReqUserRegister;
import com.sfh.req.ReqUserSearch;
import com.sfh.req.ReqUserUpdate;
import com.sfh.req.ReqVipConsumeWealth;
import com.sfh.service.Const;
import com.sfh.service.model.MassModel;
import com.sfh.service.model.NoteModel;
import com.sfh.service.model.UserModel;
import com.sfh.service.model.VIPCodeModel;
import com.sfh.service.model.table.UserTable;
import com.sfh.service.model.table.VIPCodeTable;
import com.sfh.service.util.SQLHelp;

/***
 * 用户操作
 * 
 * @author Administrator
 *
 */
public class UserController extends BaseController {
	
	/***
	 * 搜索 {@link ReqUserSearch}
	 */
	public void pageUserSearch () {
		try {
			ReqUserSearch req = this.getRequestObject(ReqUserSearch.class);
			String like = this.getEncoder(req.getContent());
			
			SQLHelp sqlHelp = new SQLHelp(UserTable.Table);
			sqlHelp.addWhereMatches(like,UserTable.nike);
			
			sqlHelp.sore("desc", UserTable.charm);

			Page<UserModel> page = UserModel.USER.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (UserModel model : page.getList()) {
				list.add(RspUser.createRspUser(model));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 财富排行 {@link ReqPage}
	 */
	public void pageWealth() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(UserTable.Table);
			sqlHelp.sore("desc", UserTable.wealth);

			Page<UserModel> page = UserModel.USER.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (UserModel model : page.getList()) {
				list.add(RspUser.createRspUser(model));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 魅力排行 {@link ReqPage}
	 */
	public void pageCharm() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(UserTable.Table);
			sqlHelp.sore("desc", UserTable.charm);

			Page<UserModel> page = UserModel.USER.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (UserModel model : page.getList()) {
				list.add(RspUser.createRspUser(model));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 注册 请求参数{@link ReqUserRegister}
	 */
	public void regiest() {
		try {
			ReqUserRegister req = this.getRequestObject(ReqUserRegister.class);
			if (StringUtil.isEmpty(req.getName())) {
				this.renderJson(ReturnData.error(1000, "账号不能为空"));
				return;
			}

			if (StringUtil.isEmpty(req.getPwd())) {
				this.renderJson(ReturnData.error(1001, "密码不能为空"));
				return;
			}
			SQLHelp sql = new SQLHelp(UserTable.Table);
			sql.addWhereEqualTo(UserTable.name, req.getName());

			if (UserModel.USER.getUserModel(sql) != null) {
				this.renderJson(ReturnData.error(1002, "账号已存在"));
				return;
			}

			UserModel user = new UserModel();
			user.setNike(this.getEncoder(req.getName()));
			user.setUrl(req.getUrl());
			user.setName(req.getName());
			user.setSex(req.getSex());
			user.setAddress(StringUtil.isEmpty(req.getAddress()) ? "保密" : req.getAddress());
			user.setPassWord(req.getPwd());
			user.setWealth(0);
			user.setCharm(0);

			// 特权时间 送60分钟
			Date vipTime = new Date();
			vipTime.setTime(60 * 60 * 1000 + vipTime.getTime());
			user.setVipTime(vipTime);

			ReturnData<?> data;
			if (user.save()) {
				data = ReturnData.ok(RspUser.createRspUser(user));
			} else {
				data = ReturnData.error(1000, "注册失败");
			}

			this.renderJson(data);

		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "注册失败,请重新注册" + e.getMessage()));
		}
	}

	/**
	 * 登录 请求参数{@link ReqUserLogin}
	 */
	public void login() {
		try {
			ReqUserLogin req = this.getRequestObject(ReqUserLogin.class);

			if (StringUtil.isEmpty(req.getName())) {
				renderJson(ReturnData.error(1000, "账号不能为空"));
				return;
			}

			if (StringUtil.isEmpty(req.getPwd())) {
				renderJson(ReturnData.error(1001, "密码不能为空"));
				return;
			}
			SQLHelp sql = new SQLHelp(UserTable.Table);
			sql.addWhereEqualTo(UserTable.name, req.getName());
			sql.addWhereEqualTo(UserTable.pwd, req.getPwd());

			UserModel user = UserModel.USER.findFirst(sql.build());
			if (user == null) {
				this.renderJson(ReturnData.error(1002, "账号或密码不正确"));
			} else {
				this.renderJson(ReturnData.ok(RspUser.createRspUser(user)));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "登录失败,请重新登录"+e));
		}

	}

	/***
	 * 查询用户信息{@link ReqQueryUser}
	 */
	public void getUser() {
		try {
			ReqQueryUser req = this.getRequestObject(ReqQueryUser.class);
			UserModel user = UserModel.USER.findById(req.getLookUserId());
			if (user == null) {
				this.renderJson(ReturnData.error(1000, "账号不能为空"));
			} else {
				this.renderJson(ReturnData.ok(RspUser.createRspUser(user)));
			}
		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "操作失败" + e.getMessage()));
		}
	}

	/***
	 * 更新信息 请求参数{@link ReqUserUpdate}
	 * 
	 */
	public void update() {
		try {
			ReqUserUpdate req = this.getRequestObject(ReqUserUpdate.class);

			if (req.getUserId() <= 0) {
				this.renderJson(ReturnData.error(1000, "请登录"));
				return;
			}

			if (StringUtil.isEmpty(req.getName())) {
				this.renderJson(ReturnData.error(1001, "昵称不能为空"));
				return;
			}

			UserModel use = new UserModel();
			use.setId(req.getUserId());
			use.setUrl(req.getHeaderURL());
			use.setNike(this.getEncoder(req.getName()));
			use.setAddress(req.getAddress());
			use.setSex(req.getSex());

			if (use.update()) {
				this.renderJson(ReturnData.ok(true));
			} else {
				this.renderJson(ReturnData.error(1003, "更新失败"));
			}
		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "信息更新失败,请重试"));
		}
	}

	/***
	 * 激活特权使用{@link ReqUserActivateVip}
	 */
	public void activateVip() {
		try {
			ReqUserActivateVip req = this.getRequestObject(ReqUserActivateVip.class);
			final UserModel user = UserModel.USER.findById(req.getUserId());
			if (user == null) {
				this.renderJson(ReturnData.error(100, "未查询到用户信息"));
				return;
			}

			SQLHelp sql = new SQLHelp(VIPCodeTable.Table);
			sql.addWhereEqualTo(VIPCodeTable.code, req.getCode());

			VIPCodeModel code = VIPCodeModel.VIP_CODE.findFirst(sql.build());
			if (code == null) {
				this.renderJson(ReturnData.error(101, "未查询相关激活码信息"));
				return;
			}
			if (code.getUserId() > 0) {
				this.renderJson(ReturnData.error(102, "激活码已被使用"));
				return;
			}

			boolean ok = Db.tx(new IAtom() {

				@Override
				public boolean run() throws SQLException {
					// 分
					Date nowDate = new Date();
					long serviceTime = code.getServiceTime();
					Date vipTime = user.getVipTime();
					if (vipTime == null) {
						vipTime = nowDate;
					} else if (vipTime.before(nowDate)) {
						vipTime = nowDate;
					}

					vipTime.setTime(serviceTime * 60 * 1000 + vipTime.getTime());
					user.setVipTime(vipTime);

					code.setUseTime(new Date());
					code.setUserId(req.getUserId());

					return user.update() && code.update();
				}
			});

			if (ok) {
				this.putTask(new TaskUserWealthCharm(req.getUserId(), Const.CHARM_VIP, Const.WEALTH_VIP));
				this.renderJson(ReturnData.ok(true));
			} else {
				this.renderJson(ReturnData.error(1000, "激活码失败,请重新激活"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "操作失败 :" + e));
		}
	}

	/***
	 * 判断特权是否可以使用 {@link ReqBase}
	 * 
	 */
	public void queryVipExpire() {
		try {
			ReqBase req = this.getRequestObject(ReqBase.class);
			UserModel user = UserModel.USER.findById(req.getUserId());
			if (user == null) {
				this.renderJson(ReturnData.error(1000, "未查询到用户信息"));
			} else {
				this.renderJson(ReturnData.ok(user.isVip()));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "未查询到相关特权"));
		}
	}

	/***
	 * 消费财富值，解密
	 */
	public void consumeWealth() {
		try {
			long createUserId;
			long wealth = 0;
			boolean success = true;
			long size=-1;
			
			ReqConsumeWealth req = this.getRequestObject(ReqConsumeWealth.class);
		
			UserModel user = UserModel.USER.findById(req.getUserId());
			if (req.getDataType() == 1) {
				NoteModel noteModel = NoteModel.NOTE.findById(req.getDataId());
				createUserId = noteModel.getUserId();
				wealth = noteModel.getWealth();
				size = user.getWealth() - wealth;
				
			}else {
				MassModel massModel = MassModel.MASS.findById(req.getDataId());
				createUserId = massModel.getUserId();
				wealth = massModel.getWealth();
				size = user.getWealth() - wealth;
			}
			
			if (size >= 0) {
				// 消费
				user.setWealth(size);
				success = user.update();
			}
			if (success) {
				this.putTask(new TaskUserWealthCharm(createUserId, 0, wealth));
				this.renderJson(ReturnData.ok(true));
			}else {
				this.renderJson(ReturnData.error(206, "解密失败"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "解密失败"));
		}
	}

	
	/***
	 *  查询社团需要财富值
	 * 
	 */
	public void queryConsume() {
		try {
			ReqConsumeWealth req = this.getRequestObject(ReqConsumeWealth.class);
			
			if (req.getUserId() <=0 ) {
				this.renderJson(ReturnData.error(ReturnData.IO, "未查询到相关信息"));
			    return;
			}
			RspConSume rsp = new RspConSume();
			UserModel user = UserModel.USER.findById(req.getUserId());
			if (user != null) {
				rsp.setUserWealth(user.getWealth());
				if (req.getDataType() == 1) {
					NoteModel noteModel = NoteModel.NOTE.findById(req.getDataId());
					rsp.setNote(RspNote.creaNote(noteModel));
				}else {
					MassModel massModel = MassModel.MASS.findById(req.getDataId());
					rsp.setMass(RspMass.createMass(massModel));
				}
				this.renderJson(ReturnData.ok(rsp));
			}else {
				this.renderJson(ReturnData.error(ReturnData.IO, "未查询到相关信息"));
			}
		
		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "未查询到相关信息"));
		}
	}

	
	/***
	 * VIP 查看特权帖子，社团获得财富值
	 * 
	 */
	public void vipConsumeWealth() {
		try {
			ReqVipConsumeWealth req = this.getRequestObject(ReqVipConsumeWealth.class);
			if (req.getUserId() == req.getCreateUserId()) {
				this.renderJson(ReturnData.ok(true));
			    return;
			}
			
			UserModel user = UserModel.USER.findById(req.getUserId());
			boolean vip = user.isVip();
			if (vip) {
				this.putTask(new TaskUserWealthCharm(req.getCreateUserId(), 0, Const.VIP_LOOK));
			}
			this.renderJson(ReturnData.ok(true));
		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "未查询到相关信息"));
		}
	}

	
	/***
	 * 更新密码 请求参数{@link ReqUpdatePwd}
	 */
	public void updatePwd() {
		try {
			ReqUpdatePwd req = this.getRequestObject(ReqUpdatePwd.class);

			if (req.getUserId() <= 0) {
				this.renderJson(ReturnData.error(1000, "账号不能为空"));
				return;
			}

			SQLHelp sql = new SQLHelp(UserTable.Table);
			sql.addWhereEqualTo(UserTable.id, req.getUserId());
			sql.addWhereEqualTo(UserTable.pwd, req.getOldPwd());

			UserModel user = UserModel.USER.findFirst(sql.build());

			if (user == null) {
				this.renderJson(ReturnData.error(1002, "账号或密码不正确"));
			} else {
				user.setPassWord(req.getNewPwd());
				if (user.update()) {
					this.renderJson(ReturnData.ok(true));
				} else {
					this.renderJson(ReturnData.error(1003, "密码更新失败"));
				}
			}
		} catch (Exception e) {
			this.renderJson(ReturnData.error(ReturnData.IO, "密码更新失败,请重试"));
		}
	}

}
